package com.tree.leetcode.hash;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName com.tree.leetcode.hash
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 1/24/24 10:05 PM
 * @Version 1.0
 */
public class LongestConsecutive {

    public static void main(String[] args) {
        int[] nums = new int[]{100,1,200,4,2,3};
        System.out.println(longestConsecutive2(nums));
    }

    public static  int longestConsecutive(int[] nums) {
        Set<Integer> num_set = new HashSet<Integer>();
        for (int num : nums) {
            num_set.add(num);
        }

        int longestStreak = 0;

        for (int num : num_set) {
            if (!num_set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                while (num_set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }

    public static  int longestConsecutive2(int[] nums) {
        Set<Integer> num_set = new HashSet<Integer>();
        for (int num : nums) {
            num_set.add(num);
        }

        int longestStreak = 0;


        for (int num : num_set) {
            int curNum = 1;
            int tmp = num;
            while (num_set.contains(tmp-1)){
                curNum +=1;
                tmp -= 1;
            }
            tmp = num;
            while (num_set.contains(tmp+1)){
                tmp +=1;
            }

            longestStreak = Math.max(longestStreak, curNum);
        }

        return longestStreak;
    }

}
